package com.binary.coder.gift.core.interfaces.sys.facade;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.binary.coder.gift.core.common.bean.BizException;
import com.binary.coder.gift.core.common.bean.ResultBean;
import com.binary.coder.gift.core.common.utils.WechatUtil;
import com.binary.coder.gift.core.interfaces.sys.dto.req.WechatLoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * @author weitao
 */
@RestController
@RequestMapping("/api/login")
public class SysLoginController {

    @Autowired
    private WechatUtil wechatUtil;

    @PostMapping("/wechat")
    public ResultBean<SaTokenInfo> login(@RequestBody WechatLoginRequest request) throws IOException {
        // 1. 调用微信接口获取 openid 和 session_key
        Map<String, String> wechatResponse = wechatUtil.code2Session(request.getCode());
        String openid = wechatResponse.get("openid");

        if (openid == null) {
            throw new BizException("登录失败，无法获取 openid");
        }
        // 2. 生成自定义登录态（如 Sa-Token）
        StpUtil.login(openid);
        return ResultBean.success(StpUtil.getTokenInfo());
    }

}
